package com.stone.springboot.websocketlog;

import com.stone.springboot.websocketlog.mybatis.mapper.DriudMapper;
import com.stone.springboot.websocketlog.mybatis.model.Driud;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.messaging.simp.user.SimpUserRegistry;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import java.security.Principal;
import java.util.List;

/**
 * Created by 喵 on 2018/1/5
 */
@Slf4j
@RestController
public class WsController {

    @Autowired
    private SimpMessagingTemplate template;

    @Autowired
    private SimpUserRegistry userRegistry;

    @Autowired
    private DriudMapper driudMapper;

    //初始在线人数
    private static int online_num = 0;
    //线程安全的socket集合


    @OnOpen
    public ResponseMessage onOpen(){
        return new ResponseMessage("连接成功");
    }

    @GetMapping("/hello")
    public ResponseMessage hello(){
        List<Driud> driuds = this.driudMapper.selectByExample(null);
        log.info("{}",driuds);

        return new ResponseMessage("Hello");
    }

    @MessageMapping("/sendTest")
    @SendTo(value = {"/topic/subscribeTest1", "/topic/subscribeTest2"})
    public ResponseMessage sendTest(User message) {
        addOnline();
        log.info("当前在线人数: {}",online_num);
        log.info("接收到了信息" + message.getName());
        return new ResponseMessage(message.getName());
    }

    @SubscribeMapping(value = {"/init/{id}"})
    public ResponseMessage sub(@DestinationVariable("id") Integer id) {
        log.info("{} 用户订阅了我。。。", id);
        return new ResponseMessage("感谢你订阅了我。。。");
    }

    @MessageMapping("/message")
    @SendToUser("/queue/message")
    public ResponseMessage toStone(User message){
        log.info(message.toString());
//        template.convertAndSendToUser("queue","/message",new ResponseMessage(message.getName()));
        return  new ResponseMessage(message.getName());
    }

    @OnClose
    public void onClose(){
        subOnline();
    }
    private synchronized void addOnline(){
        log.info("当前人数加1");
        WsController.online_num ++ ;
    }
    private synchronized void subOnline(){
        log.info("当前人数减1");
        WsController.online_num -- ;
    }

}
